$(document).ready(function() {
    // 天气图表相关变量
    let weatherChart = null;
    let currentWeatherData = null;

    // 模拟珠海历史天气数据生成函数
    function generateHistoricalWeatherData(year, month) {
        const daysInMonth = new Date(year, month, 0).getDate();
        
        const seasonalTemp = {
            winter: { min: 10, max: 20 },
            spring: { min: 15, max: 25 },
            summer: { min: 25, max: 35 },
            autumn: { min: 20, max: 30 }
        };

        const seasonalRain = {
            winter: { min: 0, max: 30 },
            spring: { min: 20, max: 100 },
            summer: { min: 50, max: 200 },
            autumn: { min: 30, max: 150 }
        };

        let season;
        switch(month) {
            case 12:
            case 1:
            case 2:
                season = 'winter';
                break;
            case 3:
            case 4:
            case 5:
                season = 'spring';
                break;
            case 6:
            case 7:
            case 8:
                season = 'summer';
                break;
            default:
                season = 'autumn';
        }

        const tempRange = seasonalTemp[season];
        const rainRange = seasonalRain[season];

        return {
            dates: Array.from({length: daysInMonth}, (_, i) => 
                `${year}-${String(month).padStart(2, '0')}-${String(i + 1).padStart(2, '0')}`
            ),
            temperatures: Array.from({length: daysInMonth}, () => 
                Math.round((Math.random() * (tempRange.max - tempRange.min) + tempRange.min) * 10) / 10
            ),
            rainfall: Array.from({length: daysInMonth}, () => 
                Math.round((Math.random() * (rainRange.max - rainRange.min) + rainRange.min) * 10) / 10
            ),
            humidity: Array.from({length: daysInMonth}, () => 
                Math.round(Math.random() * 30 + 60)
            ),
            windSpeed: Array.from({length: daysInMonth}, () => 
                Math.round(Math.random() * 20 + 5)
            )
        };
    }

    // 初始化天气图表
    function initWeatherChart() {
        const chartDom = document.getElementById('weatherChart');
        weatherChart = echarts.init(chartDom);
        
        const now = new Date();
        const currentYear = now.getFullYear();
        const currentMonth = now.getMonth() + 1;
        
        $('#weatherMonth').val(`${currentYear}-${String(currentMonth).padStart(2, '0')}`);
        $('#weatherYear').val(currentYear);
        
        updateWeatherData(currentYear, currentMonth);
    }

    // 更新天气数据和图表
    function updateWeatherData(year, month) {
        currentWeatherData = generateHistoricalWeatherData(year, month);
        
        const option = {
            title: {
                text: `珠海${year}年${month}月天气数据`,
                left: 'center',
                top: 0
            },
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    let result = params[0].axisValue + '<br/>';
                    params.forEach(param => {
                        let value = param.value;
                        let unit = '';
                        switch(param.seriesName) {
                            case '温度':
                                unit = '°C';
                                break;
                            case '降水量':
                                unit = 'mm';
                                break;
                            case '湿度':
                                unit = '%';
                                break;
                            case '风速':
                                unit = 'km/h';
                                break;
                        }
                        result += param.marker + param.seriesName + ': ' + value + unit + '<br/>';
                    });
                    return result;
                }
            },
            legend: {
                data: ['温度', '降水量', '湿度', '风速'],
                top: 30
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                top: 80,
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: currentWeatherData.dates,
                axisLabel: {
                    formatter: function(value) {
                        return value.split('-')[2];
                    }
                }
            },
            yAxis: [
                {
                    type: 'value',
                    name: '温度(°C)/湿度(%)',
                    position: 'left'
                },
                {
                    type: 'value',
                    name: '降水量(mm)',
                    position: 'right',
                    offset: 0
                },
                {
                    type: 'value',
                    name: '风速(km/h)',
                    position: 'right',
                    offset: 80
                }
            ],
            series: [
                {
                    name: '温度',
                    type: 'line',
                    smooth: true,
                    data: currentWeatherData.temperatures,
                    itemStyle: {
                        color: '#FF9F43'
                    }
                },
                {
                    name: '降水量',
                    type: 'bar',
                    yAxisIndex: 1,
                    data: currentWeatherData.rainfall,
                    itemStyle: {
                        color: '#54A0FF'
                    }
                },
                {
                    name: '湿度',
                    type: 'line',
                    smooth: true,
                    data: currentWeatherData.humidity,
                    itemStyle: {
                        color: '#00D2D3'
                    }
                },
                {
                    name: '风速',
                    type: 'line',
                    smooth: true,
                    yAxisIndex: 2,
                    data: currentWeatherData.windSpeed,
                    itemStyle: {
                        color: '#5F27CD'
                    }
                }
            ]
        };
        
        weatherChart.setOption(option);
    }

    // 日期选择事件处理
    $('#weatherMonth, #weatherYear').on('change', function() {
        const year = parseInt($('#weatherYear').val());
        const month = parseInt($('#weatherMonth').val().split('-')[1]);
        updateWeatherData(year, month);
    });

    // 导出图表为图片
    function exportChart() {
        const year = $('#weatherYear').val();
        const month = $('#weatherMonth').val().split('-')[1];
        
        const url = weatherChart.getDataURL({
            pixelRatio: 2,
            backgroundColor: '#fff'
        });
        
        const link = document.createElement('a');
        link.download = `珠海${year}年${month}月天气数据.png`;
        link.href = url;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    // 生成PDF预览
    async function generatePDF() {
        const year = $('#weatherYear').val();
        const month = $('#weatherMonth').val().split('-')[1];
        
        try {
            const $previewOverlay = $('.pdf-preview-overlay');
            const $pdfViewer = $('#pdfViewer');
            const $loadingIndicator = $('<div class="loading-indicator">正在生成PDF，请稍候...</div>');
            
            $pdfViewer.attr('src', '');
            $previewOverlay.append($loadingIndicator)
                          .css('display', 'flex')
                          .fadeIn(300);
            
            weatherChart.resize();
            await new Promise(resolve => setTimeout(resolve, 500));
            
            const doc = new jspdf.jsPDF('landscape', 'mm', 'a4', {
                filters: ['ASCIIHexEncode']
            });
            
            doc.setFont('courier', 'normal');
            doc.setFontSize(20);
            
            const [titleCanvas, detailCanvas, chartCanvas] = await Promise.all([
                (async () => {
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    ctx.font = '20px Arial';
                    const title = `珠海${year}年${month}月天气数据报告`;
                    const titleWidth = ctx.measureText(title).width;
                    canvas.width = titleWidth;
                    canvas.height = 30;
                    ctx.font = '20px Arial';
                    ctx.fillStyle = '#000000';
                    ctx.fillText(title, 0, 20);
                    return canvas;
                })(),
                
                (async () => {
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    ctx.font = '16px Arial';
                    const detailTitle = '详细数据';
                    const detailWidth = ctx.measureText(detailTitle).width;
                    canvas.width = detailWidth;
                    canvas.height = 24;
                    ctx.font = '16px Arial';
                    ctx.fillStyle = '#000000';
                    ctx.fillText(detailTitle, 0, 16);
                    return canvas;
                })(),
                
                (async () => {
                    const chartElement = document.getElementById('weatherChart');
                    return await html2canvas(chartElement, {
                        scale: 2,
                        backgroundColor: '#ffffff',
                        logging: false,
                        useCORS: true,
                        allowTaint: true,
                        width: chartElement.offsetWidth,
                        height: chartElement.offsetHeight
                    });
                })()
            ]);
            
            const titleWidth = titleCanvas.width;
            const titleImgData = titleCanvas.toDataURL('image/png');
            doc.addImage(titleImgData, 'PNG', (297 - titleWidth * 0.3) / 2, 10, titleWidth * 0.3, 10);
            
            const imgData = chartCanvas.toDataURL('image/png');
            const pageWidth = doc.internal.pageSize.getWidth();
            const imgWidth = pageWidth - 20;
            const imgHeight = (chartCanvas.height * imgWidth) / chartCanvas.width;
            doc.addImage(imgData, 'PNG', 10, 30, imgWidth, imgHeight);
            
            doc.addPage();
            
            const detailWidth = detailCanvas.width;
            const detailImgData = detailCanvas.toDataURL('image/png');
            doc.addImage(detailImgData, 'PNG', (297 - detailWidth * 0.3) / 2, 10, detailWidth * 0.3, 8);
            
            const headers = [['日期', '温度(°C)', '降水量(mm)', '湿度(%)', '风速(km/h)']];
            const data = currentWeatherData.dates.map((date, index) => [
                date,
                currentWeatherData.temperatures[index].toFixed(1),
                currentWeatherData.rainfall[index].toFixed(1),
                currentWeatherData.humidity[index],
                currentWeatherData.windSpeed[index]
            ]);
            
            doc.autoTable({
                head: headers,
                body: data,
                startY: 30,
                theme: 'grid',
                styles: {
                    font: 'courier',
                    fontSize: 8,
                    cellPadding: 2,
                    overflow: 'linebreak'
                },
                headStyles: {
                    fillColor: [102, 126, 234],
                    textColor: 255,
                    fontSize: 10,
                    fontStyle: 'bold'
                },
                alternateRowStyles: {
                    fillColor: [245, 247, 250]
                },
                margin: { top: 30 }
            });
            
            const pdfBlob = doc.output('blob');
            const pdfUrl = URL.createObjectURL(pdfBlob);
            
            $loadingIndicator.remove();
            $pdfViewer.attr('src', pdfUrl);
            
        } catch (error) {
            console.error('生成PDF时发生错误:', error);
            alert(`生成PDF预览时发生错误: ${error.message}`);
            $('.pdf-preview-overlay').fadeOut(300);
        }
    }

    // 天气按钮点击事件
    $('.weather-btn').on('click', function() {
        const $btn = $(this);
        const $container = $('.weather-chart-container');
        
        if ($container.hasClass('show')) {
            $container.removeClass('show');
            $btn.removeClass('active');
        } else {
            $container.addClass('show');
            $btn.addClass('active');
            
            if (!weatherChart) {
                initWeatherChart();
            }
        }
    });

    // 导出按钮点击事件
    $('.export-btn').on('click', exportChart);

    // PDF预览按钮点击事件
    $('.preview-pdf-btn').on('click', generatePDF);

    // 关闭按钮点击事件
    $('.weather-chart-container .chart-close').on('click', function() {
        $('.weather-btn').click();
    });

    // PDF预览关闭按钮点击事件
    $('.pdf-close-btn').on('click', function() {
        $('.pdf-preview-overlay').fadeOut(300);
    });

    // 窗口大小改变时调整图表大小
    $(window).on('resize', function() {
        if (weatherChart) {
            weatherChart.resize();
        }
    });

    // 导出变量和函数
    window.weatherChart = {
        chart: weatherChart,
        currentData: currentWeatherData,
        generatePDF: generatePDF
    };
}); 